package com.yami.shop.rights.multishop.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.model.ProdNft;
import com.yami.shop.bean.model.Product;
import com.yami.shop.bean.vo.ProdRightsVo;
import com.yami.shop.bean.vo.ProdVo;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.mystery.common.model.MysteryBox;
import com.yami.shop.mystery.common.service.MysteryBoxService;
import com.yami.shop.rights.common.dto.ProdRightsDto;
import com.yami.shop.rights.common.dto.RightExternal;
import com.yami.shop.rights.common.model.*;
import com.yami.shop.rights.common.service.*;
import com.yami.shop.rights.common.strategy.PersonRightsFactory;
import com.yami.shop.security.common.util.AuthUserContext;
import com.yami.shop.security.multishop.util.SecurityUtils;
import com.yami.shop.service.ProdNftService;
import com.yami.shop.service.ProductService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.yami.shop.common.util.ExcelUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/p/rights")
@Tag(name = "商品权益（商户端）")
@Slf4j
public class ProdRightsController {

    @Autowired
    private ProdRightsService prodRightsService;
    @Autowired
    private ProductService productService;
    @Autowired
    private ProdRightsKtService prodRightsKtService;
    @Autowired
    private ProdRightsPreemptionService prodRightsPreemptionService;
    @Autowired
    private ProdRightsExchangeService prodRightsExchangeService;
    @Autowired
    private PersonRightsFactory personRightsFactory;
    @Autowired
    private MysteryBoxService mysteryBoxService;

    @GetMapping("/list")
    @Operation(summary = "活动分页列表")
    public ServerResponseEntity<IPage<ProdRights>> pageList(ProdRightsDto vo, PageParam<ProdRights> page) {
        vo.setShopId(SecurityUtils.getShopUser().getShopId());
        IPage<ProdRights> pageData = prodRightsService.pageList(page, vo);
        return ServerResponseEntity.success(pageData);
    }

    @PostMapping("/save")
    @Operation(summary = "新增/修改活动")
    public ServerResponseEntity<Void> saveOrUpdate(@RequestBody ProdRights dto) {
        if("10".equals(dto.getType()) && ObjectUtil.isEmpty(dto.getProdId())){
            return ServerResponseEntity.showFailMsg("电子券权益请选择电子券！");
        }
        dto.setCreateAt(SecurityUtils.getShopUser().getShopId());
        personRightsFactory.saveOrUpdate(dto);
        return ServerResponseEntity.success();
    }

    @DeleteMapping
    @Operation(summary = "删除权益")
    public ServerResponseEntity<Void> deleteBrand(@RequestParam Long id) {

        // 删除权益关联主表
        UpdateWrapper<ProdRights> prodRightUpdate = new UpdateWrapper<>();
        prodRightUpdate.eq("id", id);
        prodRightUpdate.ne("status", -1);
        prodRightUpdate.set("status", -1);
        prodRightsService.update(prodRightUpdate);
        return ServerResponseEntity.success();
    }

    @GetMapping("/info/{id}")
    @Operation(summary = "获取权益详细信息")
    @Parameter(name = "id", description = "权益主键", required = true)
    public ServerResponseEntity<ProdRightsVo> info(@PathVariable("id") Long id) {
        ProdRightsVo prodRightsVo = new ProdRightsVo();
        // 获取权益信息
        ProdRights byId = prodRightsService.getById(id);
        BeanUtil.copyProperties(byId, prodRightsVo);
        // 获取权益绑定商品信息
        List<ProdVo> prodVos = new ArrayList<>();
        if("9".equals(prodRightsVo.getType())){
            List<ProdRightsPreemption> rightsProds = prodRightsPreemptionService.list(new QueryWrapper<ProdRightsPreemption>().eq("rights_id", id).eq("status", 1));
            rightsProds.forEach(s->{
                if("1".equals(s.getBlindType())){
                    QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
                    productQueryWrapper.in("prod_id",Arrays.asList(byId.getProdId().split(",")));
                    Product product = productService.getById(s.getBlindId());
                    prodVos.add(BeanUtil.copyProperties(product,ProdVo.class));
                }else {
                    MysteryBox mysteryBox = mysteryBoxService.getById(s.getBlindId());
                    ProdVo prodVo = new ProdVo();
                    prodVo.setProdId(s.getBlindId());
                    prodVo.setPic(mysteryBox.getPic());
                    prodVo.setProdName(mysteryBox.getBoxName());
                    prodVo.setStatus(mysteryBox.getStatus().longValue());
                    prodVos.add(prodVo);
                }
            });
            prodRightsVo.setProdVos(prodVos);
        }else if("11".equals(prodRightsVo.getType())){
            List<ProdRightsKt> rightsProds = prodRightsKtService.list(new QueryWrapper<ProdRightsKt>().eq("rights_id", id).eq("status", 1));
            rightsProds.forEach(s->{
                if("1".equals(s.getBlindType())){
                    QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
                    productQueryWrapper.in("prod_id",Arrays.asList(byId.getProdId().split(",")));
                    Product product = productService.getById(s.getBlindId());
                    prodVos.add(BeanUtil.copyProperties(product,ProdVo.class));
                }else {
                    MysteryBox mysteryBox = mysteryBoxService.getById(s.getBlindId());
                    ProdVo prodVo = new ProdVo();
                    prodVo.setProdId(s.getBlindId());
                    prodVo.setPic(mysteryBox.getPic());
                    prodVo.setProdName(mysteryBox.getBoxName());
                    prodVo.setStatus(mysteryBox.getStatus().longValue());
                    prodVos.add(prodVo);
                }
            });
            prodRightsVo.setProdVos(prodVos);
        }else if("12".equals(prodRightsVo.getType())){
            List<ProdRightsExchange> rightsProds = prodRightsExchangeService.list(new QueryWrapper<ProdRightsExchange>().eq("rights_id", id).eq("status", 1));
            rightsProds.forEach(s->{
                if("1".equals(s.getBlindType())){
                    QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
                    productQueryWrapper.in("prod_id",Arrays.asList(byId.getProdId().split(",")));
                    Product product = productService.getById(s.getBlindId());
                    prodVos.add(BeanUtil.copyProperties(product,ProdVo.class));
                }else {
                    MysteryBox mysteryBox = mysteryBoxService.getById(s.getBlindId());
                    ProdVo prodVo = new ProdVo();
                    prodVo.setProdId(s.getBlindId());
                    prodVo.setPic(mysteryBox.getPic());
                    prodVo.setProdName(mysteryBox.getBoxName());
                    prodVo.setStatus(mysteryBox.getStatus().longValue());
                    prodVos.add(prodVo);
                }
            });
            prodRightsVo.setProdVos(prodVos);
        }


        return ServerResponseEntity.success(prodRightsVo);
    }

    @GetMapping("/getList")
    @Operation(summary = "权益列表")
    public ServerResponseEntity<List<ProdRightsVo>> getList(@ParameterObject ProdRights vo) {
        vo.setCreateAt(AuthUserContext.get().getShopId());
        List<ProdRightsVo> pageRule = prodRightsService.getList(vo);
        return ServerResponseEntity.success(pageRule);
    }

    @RequestMapping("inExeclRightExternal")
    public ServerResponseEntity<Map<String, Object>> inExeclRightExternal(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        List<RightExternal> list = ExcelUtils.importExcel(file, 0, 1, RightExternal.class);
        if (list == null || list.size() == 0) {
            return ServerResponseEntity.showFailMsg("文件格式不对");
        }
        // 判空
        List<String> emptys = list.stream().filter(s -> ObjectUtil.isEmpty(s.getCode())).map(RightExternal::getCode).collect(Collectors.toList());
        if(ObjectUtil.isNotEmpty(emptys) || emptys.size() > 0) {
            return ServerResponseEntity.showFailMsg("导入文件中含有空值!");
        }
        List<String> collect = list.stream().map(RightExternal::getCode).collect(Collectors.toList());
        map.put("codeData", String.join(",",collect));
        map.put("size", collect.size());
        return ServerResponseEntity.success(map);
    }

}
